﻿using System;
using System.Net;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace BallMadness
{
    public class EnemyManager
    {
        public static Texture2D paw;
        public static Texture2D shadow;

        TimeSpan timeToSpawnNext;
        TimeSpan spawnDelay = new TimeSpan(0, 0, 7);

        TimeSpan spawnInc = new TimeSpan(0, 0, 0, 0, 200);
        TimeSpan spawnMin = new TimeSpan(0, 0, 2);

        private List<Enemy> enemies;

        public EnemyManager()
        {
            enemies = new List<Enemy>();
            timeToSpawnNext = spawnDelay;
        }

        public void OnNavigateTo(ContentManager manager)
        {
            paw = manager.Load<Texture2D>("paw");
            shadow = manager.Load<Texture2D>("shadow");
        }

        public void Reset()
        {
            enemies.Clear();
            timeToSpawnNext = spawnDelay;
            spawnDelay = new TimeSpan(0, 0, 7);
        }

        public void OnUpdate(GameTimerEventArgs e)
        {
            timeToSpawnNext -= e.ElapsedTime;
            if (timeToSpawnNext <= TimeSpan.Zero && !ScoreManager.gameOver)
            {
                enemies.Add(new Enemy());
                timeToSpawnNext = spawnDelay;
                spawnDelay -= spawnInc;
                if (spawnDelay < spawnMin) spawnDelay = spawnMin;
            }

            for (int c = enemies.Count - 1; c >= 0; c--)
            {
                enemies[c].OnUpdate(e);
                if (enemies[c].isExpired())
                {
                    enemies.RemoveAt(c);
                }
            }
        }

        public void OnDraw(SpriteBatch spriteBatch)
        {
            foreach (Enemy e in enemies)
                if (!e.isHit())
                    e.OnDraw(spriteBatch);

            foreach (Enemy e in enemies)
                if (e.isHit())
                    e.OnDraw(spriteBatch);
        }

        public void DoCollision(int radius, Vector2 position)
        {
            for (int c = enemies.Count - 1; c >= 0; c--)
            {
                if (enemies[c].isHit())
                {
                    if (shadow.Height / 2 + radius > Vector2.Distance(position, enemies[c].position))
                    {
                        if (!ScoreManager.gameOver) ScoreManager.death.Play();
                        ScoreManager.gameOver = true;
                    }
                }
            }
        }
    }
}
